﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace HBattle
{
    public class StateMachine<T> where T : BaseGameEntity
    {
        private T Owner;

        private State<T> currentState;

        private State<T> previousState;

        private State<T> globalState;

        public StateMachine(T owner)
        {
            Owner = owner;
        }

        public State<T> CurrentState
        {
            get
            {
                return currentState; 
            }
            set
            {
                currentState = value;
            }
        }
        public State<T> GlobalState
        {
            get
            {
                return globalState;
            }
            set
            {
                globalState = value;
            }
        }

        public State<T> PreviousState
        {
            get
            {
                return previousState;
            }
            set
            {
                previousState = value;
            }
        }

        public void Update()
        {
            globalState.Excute(Owner);
            currentState.Excute(Owner);
        }

        public void ChangeState(State<T> newState)
        {
            if (newState == null)
            {
                throw new System.Exception("newState Error");
            }
            if (currentState != null)
            {
                previousState = currentState;
                currentState.Exit(Owner);
            }

            currentState = newState;
            currentState.Enter(Owner);
        }

        public void RevertToPreviousState()
        {
            if (previousState == null)
            {
                throw new System.Exception("previousState Error");
            }

            ChangeState(previousState);
        }

        public bool IsInState(State<T> state)
        {
            return state == currentState;
        }

        public bool HandleMessage(Telegram msg)
        {
            if (currentState != null && currentState.OnMessage(Owner, msg))
            {
                return true;
            }

            if (globalState != null && globalState.OnMessage(Owner, msg))
            {
                return true;
            }

            return false;
        }
    }
}

